#include "../inc/serial.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

int serial_open(const char *device, const SerialConfig *config) {
    int fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0) {
        perror("Failed to open serial port");
        return -1;
    }

    struct termios options;
    tcgetattr(fd, &options);

    // 设置波特率
    cfsetispeed(&options, config->baud_rate);
    cfsetospeed(&options, config->baud_rate);

    // 设置数据位
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    // 设置校验位
    switch (config->parity) {
        case 'N':
            options.c_cflag &= ~PARENB;
            break;
        case 'E':
            options.c_cflag |= PARENB;
            options.c_cflag &= ~PARODD;
            break;
        case 'O':
            options.c_cflag |= PARENB;
            options.c_cflag |= PARODD;
            break;
    }

    // 设置停止位
    if (config->stop_bits == 2)
        options.c_cflag |= CSTOPB;
    else
        options.c_cflag &= ~CSTOPB;

    // 其他设置
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;

    tcsetattr(fd, TCSANOW, &options);

    return fd;
}

int serial_read(int fd, uint8_t *buffer, size_t length) {
    return read(fd, buffer, length);
}

int serial_write(int fd, const uint8_t *data, size_t length) {
    return write(fd, data, length);
}

void serial_close(int fd) {
    close(fd);
}